import React, {Component} from 'react';
import {
    NativeModules
} from 'react-native';

import {StackActions, NavigationActions} from 'react-navigation';
import SplashScreen from 'react-native-splash-screen'

import store from '../store/store';
import Global from '../common/global';
import * as TYPES from '../common/type'
import Util from '../common/util'
import Login from './Login'
import {loginSuccess} from '../actions/mineAction'
import {Initializer} from "react-native-baidumap-sdk/lib/js/index";

const resetAction = StackActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({routeName: 'Tab'})
    ]
})

export default class Splash extends Component {

    static navigationOptions = {
        header: null
    }

    constructor(props) {
        super(props);
        this.state = {
            netError: false,
            url: '',
            initurl: '',
            index: 0,
            status: 'No Page Loaded',
            backButtonEnabled: false,
            forwardButtonEnabled: false,
            loading: true,
            scalesPageToFit: true,
            time: 4
        }
    }

    componentDidMount() {
        if (!store.getState().App.initialed) {
            this.init()

        } else {
            setTimeout(() => {
                SplashScreen.hide();
            }, 500)
        }
    }

    init = () => {
        store.dispatch({
            type: TYPES.INITIAL_APP
        })
        if(Global.OS == 'android') {
            NativeModules.UpdateApp.updateDialog();
        }
        Initializer.init('db3ckhVEglzHEGOgPp6zUbPgChfzMKx5').catch(e => console.error(e))
        this.autoLogin()
    }

    autoLogin = () => {
        if (!Global.uid) {
            Global.storage.load({
                key: 'user'
            }).then(ret => {
                Util.fetchPost(Api.loginUrl, ret)
                    .then(({code, msg, data}) => {
                        if (code == '0') {
                            store.dispatch(loginSuccess(data));
                            this.hideAndReset()
                        } else {
                            this.hideSplashScreen()
                        }
                    }).catch(error => {
                    console.log(error);
                    this.hideSplashScreen()
                });
            }).catch(error => {
                this.hideSplashScreen()
            });
        }
    }

    hideAndReset = () => {
        this.props.navigation.dispatch(resetAction);
        this.hideSplashScreen()
    }

    hideSplashScreen = () => {
        setTimeout(() => {
            SplashScreen.hide();
        }, 500)
    }

    render() {
        return (
            <Login navigation={this.props.navigation}/>
        );
    }
}
